package com.Xht.www.dao;

import com.Xht.www.po.UserHistoryOrdersPO;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserHistoryOrdersDAO extends BaseDAO {

    // 插入订单记录
    public boolean insertOrder(UserHistoryOrdersPO order) {
        if (!isValidOrder(order)) {
            return false;
        }
        String sql = "INSERT INTO user_history_orders (user_id, merchant_name, contact_phone, total_consumption, room_type_name, bed_type, room_type_quantity, order_placement_time, check_in_time, check_out_time, order_status, remarks) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, order.getUserId());
            pstmt.setString(2, order.getMerchantName());
            pstmt.setString(3, order.getContactPhone());
            pstmt.setBigDecimal(4, order.getTotalConsumption());
            pstmt.setString(5, order.getRoomTypeName());
            pstmt.setString(6, order.getBedType());
            pstmt.setInt(7, order.getRoomTypeQuantity());
            pstmt.setTimestamp(8, order.getOrderPlacementTime());
            pstmt.setTimestamp(9, order.getCheckInTime());
            pstmt.setTimestamp(10, order.getCheckOutTime());
            pstmt.setString(11, order.getOrderStatus());
            pstmt.setString(12, order.getRemarks());
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            releaseConnection(connection);
        }
    }


    // 根据订单 ID 查询订单记录
    public UserHistoryOrdersPO getOrderById(int orderId) {
        String sql = "SELECT * FROM user_history_orders WHERE order_id = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, orderId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    UserHistoryOrdersPO order = new UserHistoryOrdersPO();
                    order.setOrderId(rs.getInt("order_id"));
                    order.setUserId(rs.getInt("user_id"));
                    order.setMerchantName(rs.getString("merchant_name"));
                    order.setContactPhone(rs.getString("contact_phone"));
                    order.setTotalConsumption(rs.getBigDecimal("total_consumption"));
                    order.setRoomTypeName(rs.getString("room_type_name"));
                    order.setBedType(rs.getString("bed_type"));
                    order.setRoomTypeQuantity(rs.getInt("room_type_quantity"));
                    order.setOrderPlacementTime(rs.getTimestamp("order_placement_time"));
                    order.setCheckInTime(rs.getTimestamp("check_in_time"));
                    order.setCheckOutTime(rs.getTimestamp("check_out_time"));
                    order.setOrderStatus(rs.getString("order_status"));
                    order.setRemarks(rs.getString("remarks"));
                    return order;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseConnection(connection);
        }
        return null;
    }

    // 更新订单记录
    public boolean updateOrder(UserHistoryOrdersPO order) {
        if (!isValidOrder(order)) {
            return false;
        }
        String sql = "UPDATE user_history_orders SET user_id = ?, merchant_name = ?, contact_phone = ?, total_consumption = ?, room_type_name = ?, bed_type = ?, room_type_quantity = ?, order_placement_time = ?, check_in_time = ?, check_out_time = ?, order_status = ?, remarks = ? WHERE order_id = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, order.getUserId());
            pstmt.setString(2, order.getMerchantName());
            pstmt.setString(3, order.getContactPhone());
            pstmt.setBigDecimal(4, order.getTotalConsumption());
            pstmt.setString(5, order.getRoomTypeName());
            pstmt.setString(6, order.getBedType());
            pstmt.setInt(7, order.getRoomTypeQuantity());
            pstmt.setTimestamp(8, order.getOrderPlacementTime());
            pstmt.setTimestamp(9, order.getCheckInTime());
            pstmt.setTimestamp(10, order.getCheckOutTime());
            pstmt.setString(11, order.getOrderStatus());
            pstmt.setString(12, order.getRemarks());
            pstmt.setInt(13, order.getOrderId());
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            releaseConnection(connection);
        }
    }

    // 检验订单信息是否合法
    private boolean isValidOrder(UserHistoryOrdersPO order) {
        if (order.getUserId() == null || order.getUserId() <= 0) {
            return false;
        }
        if (order.getMerchantName() == null || order.getMerchantName().isEmpty()) {
            return false;
        }
        if (order.getContactPhone() == null || order.getContactPhone().isEmpty()) {
            return false;
        }
        if (order.getTotalConsumption() == null || order.getTotalConsumption().compareTo(BigDecimal.ZERO) < 0) {
            return false;
        }
        if (order.getRoomTypeName() == null || order.getRoomTypeName().isEmpty()) {
            return false;
        }
        if (order.getBedType() == null || order.getBedType().isEmpty()) {
            return false;
        }
        if (order.getRoomTypeQuantity() == null || order.getRoomTypeQuantity() <= 0) {
            return false;
        }
        if (order.getOrderPlacementTime() == null) {
            return false;
        }
        if (order.getCheckInTime() == null || order.getCheckOutTime() == null || order.getCheckInTime().after(order.getCheckOutTime())) {
            return false;
        }
        return order.getOrderStatus() != null && !order.getOrderStatus().isEmpty();
    }

    // 根据用户 ID 查询订单记录
    public List<UserHistoryOrdersPO> getAllOrdersByUserId(int userId) {
        List<UserHistoryOrdersPO> orders = new ArrayList<>();
        String sql = "SELECT * FROM user_history_orders WHERE user_id = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    UserHistoryOrdersPO order = new UserHistoryOrdersPO();
                    order.setOrderId(rs.getInt("order_id"));
                    order.setUserId(rs.getInt("user_id"));
                    order.setMerchantName(rs.getString("merchant_name"));
                    order.setContactPhone(rs.getString("contact_phone"));
                    order.setTotalConsumption(rs.getBigDecimal("total_consumption"));
                    order.setRoomTypeName(rs.getString("room_type_name"));
                    order.setBedType(rs.getString("bed_type"));
                    order.setRoomTypeQuantity(rs.getInt("room_type_quantity"));
                    order.setOrderPlacementTime(rs.getTimestamp("order_placement_time"));
                    order.setCheckInTime(rs.getTimestamp("check_in_time"));
                    order.setCheckOutTime(rs.getTimestamp("check_out_time"));
                    order.setOrderStatus(rs.getString("order_status"));
                    order.setRemarks(rs.getString("remarks"));
                    orders.add(order);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseConnection(connection);
        }
        return orders;
    }

    // 根据商家名称和订单状态查询订单记录
    public List<UserHistoryOrdersPO> getAllOrdersByMerchantNameAndStatus(String merchantName, String status) {
        List<UserHistoryOrdersPO> orders = new ArrayList<>();
        String sql = "SELECT * FROM user_history_orders WHERE merchant_name = ? AND order_status = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, merchantName);
            pstmt.setString(2, status);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    UserHistoryOrdersPO order = new UserHistoryOrdersPO();
                    order.setOrderId(rs.getInt("order_id"));
                    order.setUserId(rs.getInt("user_id"));
                    order.setMerchantName(rs.getString("merchant_name"));
                    order.setContactPhone(rs.getString("contact_phone"));
                    order.setTotalConsumption(rs.getBigDecimal("total_consumption"));
                    order.setRoomTypeName(rs.getString("room_type_name"));
                    order.setBedType(rs.getString("bed_type"));
                    order.setRoomTypeQuantity(rs.getInt("room_type_quantity"));
                    order.setOrderPlacementTime(rs.getTimestamp("order_placement_time"));
                    order.setCheckInTime(rs.getTimestamp("check_in_time"));
                    order.setCheckOutTime(rs.getTimestamp("check_out_time"));
                    order.setOrderStatus(rs.getString("order_status"));
                    order.setRemarks(rs.getString("remarks"));
                    orders.add(order);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseConnection(connection);
        }
        return orders;
    }

    // 更新订单状态和备注
    public boolean updateOrderStatusAndRemark(int orderId, String status, String remark) {
        String sql = "UPDATE user_history_orders SET order_status = ?, remarks = ? WHERE order_id = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, status);
            pstmt.setString(2, remark);
            pstmt.setInt(3, orderId);
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            releaseConnection(connection);
        }
    }
}

